package cn.itlight.pet.service.impl;


import cn.itlight.pet.domain.PetType;
import cn.itlight.pet.mapper.PetTypeMapper;
import cn.itlight.pet.service.IPetTypeService;
import cn.itlight.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tomliu
 * @since 2022-07-16
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;
    @Override
    public List<PetType> tree() {
        // 1.一次性查询出全部数据
        List<PetType> pts = petTypeMapper.loadAll();

        // 2.创建一个集合对象，用于放最终排列完成的树数据
        List<PetType> ptTree = new ArrayList<PetType>();

        // 3.将集合数据换转为map，消除时间复杂度问题
        // Map<Long, PetType> ptMap = ptTree.stream().collect(Collectors.toMap(PetType::getId, item -> item));
        HashMap<Long, PetType> ptMap = new HashMap<>();
        for (PetType petType : pts) {
            ptMap.put(petType.getId(), petType);
        }

        for (PetType pt : pts){
            if (pt.getPid() ==null){
                ptTree.add(pt);
            } else {
                // 从map集合中获取到父对象，将自己添加到父对象的children集合中
                PetType petType = ptMap.get(pt.getPid());
                if (petType != null){
                    petType.getChildren().add(pt);
                }
            }

        }
        return ptTree;
    }


}
